import time

import yaml
from selenium import webdriver

from utils.log_util import logger


class BaseDriver:
    def __init__(self,driver = None):
        if driver is None:
            # 实例化
            self.driver = webdriver.Chrome()
            # 隐式等待
            self.driver.implicitly_wait(10)
            # 打开cookie.yaml文件，将值赋值给cookies
            with open('../cookie.yaml', encoding='utf-8') as f:
                cookies = yaml.safe_load(f)
            # 打开网页
            self.driver.get('https://work.weixin.qq.com/wework_admin/frame#index')
            for cookie in cookies:
                self.driver.add_cookie(cookie)
            self.driver.get('https://work.weixin.qq.com/wework_admin/frame#index')
        else:
            self.driver = driver
    # 封装找到指定元素的方法
    def find(self,by,value):
        return self.driver.find_element(by,value)

    # 封装找到指定元素并点击的方法
    def find_and_click(self,by,value):
        self.find(by,value).click()

    # 封装找到指定元素并输入数据的方法
    def find_and_send_keys(self,by,value,name):
        self.find(by,value).send_keys(name)

    def finds(self, by, value=None):
        if isinstance(by,tuple):
            return self.driver.find_elements(*by)
        else:
            return self.driver.find_elements(by, value)

    def wait_element_show(self,click_element,waite_element):
        n = 1

        while True:
            user = self.finds(waite_element)#By.ID, 'username'
            logger.info(f'第{n}次点击')
            if len(user) < 1:
                ele = self.finds(click_element)#By.CSS_SELECTOR, ".ww_operationBar .js_add_member"
                ele[0].click()
                n+=1
            else:
                break
    def close_win(self):
        self.driver.quit()


    def find_name(self,get_element,next_element,name):
        while True:
            result = []
            ele = self.finds(get_element)
            # ele = self.driver.find_elements(By.CSS_SELECTOR, '.js_list td:nth-child(2)')
            for e in ele:
                result.append(e.text)
            print(result)
            if name in result:
                break
            else:
                time.sleep(2)
                ele = self.finds(next_element)
                # ele = self.driver.find_elements(By.XPATH, "//*[@class='ww_pageNav_info_arrowWrap js_next_page']")
                ele[0].click()
        return result